package com.sesame.service;

import com.sesame.api.FMSConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class NodeService {

    @Autowired
    private FMSConfig fmsConfig;

    public List<Map> queryNodes(String path) {
        File file = new File(path);
        return searchfile(file, null);
    }

    private List<Map> searchfile(File file, String parentId) {
        List<Map> listAll = new ArrayList<Map>();
        File[] files = file.listFiles();
        for (int i = 0; i < files.length; i++) {
            File f = files[i];

            String path = f.getAbsolutePath();
            String key = path.hashCode() + "";

            Map map = new HashMap();
            map.put("key", key);
            map.put("parentId", parentId);
            map.put("title", f.getName());
            map.put("path", path);
            map.put("dir", f.isDirectory());
            map.put("src", path.replace(fmsConfig.getFilePath(), fmsConfig.getMapping()));

            if (f.isDirectory()) {
                List<Map> list = searchfile(f, key);
                map.put("children", list);
            }
            listAll.add(map);
        }
        return listAll;
    }
}
